package com.lbt.mybatis.plus.extend.bean;

import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhangjinyu
 * @since 2023-05-18
 */
public class MPEBoundSql {
    private final Configuration configuration;
    @Getter
    private final List<ParameterMapping> mappings;
    private final BoundSql boundSql;
    @Setter
    private String sql;

    private MPEBoundSql(Configuration configuration, BoundSql boundSql) {
        this.configuration = configuration;
        this.boundSql = boundSql;
        this.mappings = new ArrayList<>();
    }

    public static MPEBoundSql of(Configuration configuration, BoundSql boundSql) {
        return new MPEBoundSql(configuration, boundSql);
    }

    public void addProperties(String name, Object value) {
        mappings.add(new ParameterMapping.Builder(configuration, name, value.getClass()).build());
        boundSql.setAdditionalParameter(name, value);
    }

    public String getSql() {
        return Objects.isNull(sql) ? boundSql.getSql() : sql;
    }
}
